package com.chebaohui.iqs.service.impl.deal.bihu;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.chebaohui.iqs.config.CompanyValue;
import com.chebaohui.iqs.config.ResultCode;
import com.chebaohui.iqs.entity.base.Cars;
import com.chebaohui.iqs.entity.req.CheckCar;
import com.chebaohui.iqs.entity.res.CompanyCars;
import com.chebaohui.iqs.service.impl.deal.bihu.profess.BiHuCarCheck;

/**
 * 壁虎线程
 * 
 * @author xielonghai
 *
 */
public class BiHuCarThread extends Thread {

	private CheckCar carParam;// 查车参数

	private Map<String, Boolean> mapCode;// 所需返回保险公司编码集合

	private List<CompanyCars<List<Cars>>> result;// 查车结果

	private long timeDeal = 0l;// 线程处理时间

	public BiHuCarThread(CheckCar carParam, Map<String, Boolean> mapCode) {
		super();
		this.mapCode = mapCode;
		this.carParam = carParam;
	}

	/**
	 * 线程启动
	 */
	@Override
	public void run() {
		long begin = new Date().getTime();
		checkCar();
		timeDeal = new Date().getTime() - begin;
	}

	/**
	 * 查车
	 */
	private void checkCar() {
		try {
			result = new BiHuCarCheck(carParam, mapCode).bhCheckCar();
		} catch (Exception e) {
			result = new ArrayList<>();
			for (String key : mapCode.keySet()) {
				if (mapCode.get(key)) {
					CompanyCars<List<Cars>> c = new CompanyCars<List<Cars>>(key, ResultCode.N02.getCode(),
							ResultCode.N02.getMsg() + e.getMessage());
					result.add(c);
				}
			}
		}
	}

	/**
	 * 获取查车结果 并关闭线程
	 * 
	 * @return
	 */
	public List<CompanyCars<List<Cars>>> getCars() {
		int time = 0;
		while (true) {
			if (!this.isAlive() || time >= CompanyValue.maxTime)
				break;

			time++;
			try {
				Thread.sleep(1000);// 每隔1秒查看线程是否完成
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		try {
			if (this.isAlive()) {// 关闭线程
				this.interrupt();
				this.join();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (null == result || result.isEmpty()) {
			result = new ArrayList<>();
			for (String key : mapCode.keySet()) {
				if (mapCode.get(key)) {
					CompanyCars<List<Cars>> c = new CompanyCars<List<Cars>>(key, ResultCode.N02.getCode(),
							ResultCode.N02.getMsg() + "线程处理超时");
					result.add(c);
				}
			}
		}

		return result;
	}

	/**
	 * 线程处理时间
	 * 
	 * @return
	 */
	public long getTimeDeal() {
		return timeDeal;
	}
}
